package org.geektimes.projects.user.config;

import org.geekbang.projects.config.source.AbstractConfigSource;
import org.geekbang.projects.injection.ApplicationContext;
import org.geekbang.projects.injection.Component;
import org.geekbang.projects.injection.processor.ApplicationContextAware;

import javax.annotation.PostConstruct;
import javax.naming.Context;
import java.util.*;

/**
* 基于jndi的配置源  
* @author : KangNing Hu
*/
@Component
public class JNDIConfigSource extends AbstractConfigSource implements ApplicationContextAware {

	private Map<String , String> environment= new HashMap<>();

	private ApplicationContext applicationContext;

	public JNDIConfigSource() {
		super(350, "jndi environment");
	}

	@PostConstruct
	public void init() throws Exception {
		List<String> nameAll = applicationContext.listNames("/");
		Context context = applicationContext.getContext();
		for (String name : nameAll){
			if (!name.contains("/")) {
				environment.put(name, context.lookup(name).toString());
			}
		}
	}

	@Override
	protected Map<String, String> getSource() throws Throwable {
		return environment;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}
}
